<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑法律条款' : '新增法律条款'"
    width="70%"
    :before-close="handleClose"
  >
    <div class="law-form">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="法律代码" prop="lawCode">
              <el-input
                v-model="formData.lawCode"
                placeholder="请输入法律代码，如：刑法第123条"
                maxlength="100"
                show-word-limit
              />
              <div class="form-tip">示例：刑法第123条、民法典第456条</div>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effectiveDate">
              <el-date-picker
                v-model="formData.effectiveDate"
                type="datetime"
                placeholder="请选择生效日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="条款内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            placeholder="请输入法律条款的具体内容"
            :rows="6"
            maxlength="2000"
            show-word-limit
          />
          <div class="form-tip">请输入法律条款的详细内容，包括条款条文、适用范围等</div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联分类" prop="categoryId">
              <el-cascader
                v-model="formData.categoryId"
                :options="categoryTree"
                :props="{ value: 'id', label: 'name', children: 'children', emitPath: false }"
                placeholder="请选择分类"
                clearable
                filterable
                style="width: 100%"
                @focus="fetchCategories"
              />
              <div class="form-tip">选择该条款所属的法律分类</div>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="关联文档" prop="documentId">
              <el-select
                v-model="formData.documentId"
                placeholder="请选择关联的法律文档"
                filterable
                clearable
                style="width: 100%"
                @focus="fetchDocuments"
              >
                <el-option
                  v-for="doc in documentOptions"
                  :key="doc.id"
                  :label="doc.title"
                  :value="doc.id"
                >
                  <div class="document-option">
                    <span class="doc-title">{{ doc.title }}</span>
                    <el-tag :type="getDocTypeTagType(doc.docType)" size="small">
                      {{ DOC_TYPES[doc.docType] }}
                    </el-tag>
                  </div>
                </el-option>
              </el-select>
              <div class="form-tip">选择与此条款相关的法律文档</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { createLaw, updateLaw } from '../../../api/law'
import { getCategoryList } from '../../../api/category'
import { getDocumentPage, DOC_TYPES } from '../../../api/document'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  lawData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'refresh'])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单引用
const formRef = ref()

// 是否编辑模式
const isEdit = computed(() => !!props.lawData?.id)

// 提交加载状态
const submitLoading = ref(false)

// 分类树数据
const categoryTree = ref([])

// 文档选项
const documentOptions = ref([])

// 表单数据
const formData = reactive({
  id: null,
  lawCode: '',
  content: '',
  effectiveDate: '',
  documentId: null,
  categoryId: null
})

// 表单验证规则
const formRules = {
  lawCode: [
    { required: true, message: '请输入法律代码', trigger: 'blur' },
    { max: 100, message: '法律代码不能超过100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入条款内容', trigger: 'blur' },
    { max: 2000, message: '条款内容不能超过2000个字符', trigger: 'blur' }
  ],
  effectiveDate: [
    { required: true, message: '请选择生效日期', trigger: 'change' }
  ]
}

// 构建分类树
const buildCategoryTree = (categories) => {
  const tree = []
  const map = new Map()
  
  // 先创建所有节点的映射
  categories.forEach(category => {
    map.set(category.id, { 
      ...category, 
      children: [] 
    })
  })
  
  // 构建树形结构
  categories.forEach(category => {
    const node = map.get(category.id)
    if (category.parentId === 0) {
      // 顶级分类
      tree.push(node)
    } else {
      // 子分类
      const parent = map.get(category.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })
  
  return tree
}

// 获取文档类型标签样式
const getDocTypeTagType = (docType) => {
  const typeMap = {
    0: 'danger',   // 法律 - 红色
    1: 'primary',  // 案例 - 蓝色
    2: 'warning',  // 判决书 - 橙色
    3: 'success'   // 文章 - 绿色
  }
  return typeMap[docType] || 'info'
}

// 获取分类列表
const fetchCategories = async () => {
  if (categoryTree.value.length > 0) return
  
  try {
    const response = await getCategoryList()
    if (response.code === 200) {
      categoryTree.value = buildCategoryTree(response.data)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取文档列表
const fetchDocuments = async () => {
  if (documentOptions.value.length > 0) return
  
  try {
    const response = await getDocumentPage({ pageNum: 1, pageSize: 1000 })
    if (response.code === 200) {
      documentOptions.value = response.data.records
    }
  } catch (error) {
    console.error('获取文档列表失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    lawCode: '',
    content: '',
    effectiveDate: '',
    documentId: null,
    categoryId: null
  })
  formRef.value?.resetFields()
}

// 关闭对话框
const handleClose = () => {
  resetForm()
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    submitLoading.value = true
    
    const submitData = { ...formData }
    
    let response
    if (isEdit.value) {
      response = await updateLaw(submitData)
    } else {
      delete submitData.id
      response = await createLaw(submitData)
    }

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      emit('refresh')
      handleClose()
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 监听法律条款数据变化，回填表单
watch(() => props.lawData, (newData) => {
  if (newData) {
    Object.assign(formData, {
      id: newData.id,
      lawCode: newData.lawCode || '',
      content: newData.content || '',
      effectiveDate: newData.effectiveDate || '',
      documentId: newData.documentId || null,
      categoryId: newData.categoryId || null
    })
  }
}, { immediate: true })

// 监听对话框打开，获取数据
watch(dialogVisible, (visible) => {
  if (visible) {
    fetchCategories()
    fetchDocuments()
  } else {
    resetForm()
  }
})
</script>

<style scoped>
.law-form {
  padding: 0 20px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
  line-height: 1.4;
}

.document-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.doc-title {
  flex: 1;
  margin-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
  line-height: 1.6;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .law-form {
    padding: 0 10px;
  }
  
  :deep(.el-form-item__label) {
    line-height: 1.2;
  }
  
  .el-col {
    width: 100%;
  }
}
</style>
